package controller

import (
	"fmt"
	"goapp-web-server/app/middleware/jwt"
	"goapp-web-server/app/service"
	"goapp-web-server/app/utils/validator"

	"github.com/kataras/iris"
)

type SysUserController struct {
	Service service.SysUserService
}
type Params struct {
	Username string `json:"username" valid:"mobile,required"`
	Password string `json:"password" valid:"required"`
}

// login
func (c *SysUserController) PostLogin(ctx iris.Context) {
	var params Params
	err := ctx.ReadJSON(&params)
	if err != nil {
		ctx.StatusCode(iris.StatusBadRequest)
		ctx.WriteString(err.Error())
	}
	valid, errors := validator.Validate(params)
	if !valid {
		fmt.Println(errors)
		ctx.StatusCode(iris.StatusUnprocessableEntity)
		ctx.JSON(iris.Map{"code": 422, "errors": errors, "message": "参数验证失败"})
		return
	}
	user, err := c.Service.Login(params.Username, params.Password)
	if err != nil {
		ctx.JSON(iris.Map{"code": -1, "message": "用户名或密码不正确"})
		return
	}
	data := make(map[string]interface{}, 0)
	data["userid"] = user.ID
	data["username"] = user.UserName
	token := jwt.CreateToken(data)
	ctx.Header("access-token", token)
	ctx.JSON(user)
}

// user list
func (c *SysUserController) Get(ctx iris.Context) {
	data, _ := c.Service.GetAll()
	ctx.JSON(iris.Map{"code": 0, "data": data})
}

// create user
func (c *SysUserController) Post(ctx iris.Context) string {
	data := jwt.GetUser(ctx)
	fmt.Println("username", data["username"])
	return `create`
}

// get uesr by id
func (c *SysUserController) GetBy(id string, ctx iris.Context) {
	data, _ := c.Service.GetByID(id)
	ctx.JSON(iris.Map{"code": 0, "data": data})
}

// update user by id
func (*SysUserController) PutBy(id string) string {
	return `update {id}`
}

// delete user by id
func (*SysUserController) DeleteBy(id string) string {
	return `delete {id}`
}
